package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.adapter.FollowPhotoAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.FollowInfoBean;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.DateTimeDialog;
import com.bjesc_b2c.app.appraiset.widget.layout.FlowRadioGroup;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.example.codeutils.utils.TimeUtils;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.CustomLog;
import com.rxretrofit_build.util.MapUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.Bind;
import butterknife.OnClick;
import master_bean.CarSourcePhotoBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.bjesc_b2c.app.appraiset.R.id.rlty_def_reason;
import static com.bjesc_b2c.app.appraiset.utils.BitmapUtil.copyFile;
import static com.bjesc_b2c.app.appraiset.utils.TimeListUilts.getObjectKey;

/**
 * Created by yidong on 2017/5/27.
 */

public class FollowActivity extends BaseActivity implements DateTimeDialog.MyOnDateSetListener, RadioGroup.OnCheckedChangeListener, MultiItemTypeAdapter.OnItemClickListener {
    @Bind(R.id.ed_follow_content)
    EditText contentEdit;
    @Bind(R.id.edit_fail_summary)
    EditText summaryEdit;
    @Bind(R.id.tv_title)
    TextView title;
    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.fail_summary_linear)
    LinearLayout failLin;
    @Bind(R.id.tv_next_time)
    TextView nextTimeTV;
    @Bind(R.id.rg_client_type)
    RadioGroup typeRadio;
    @Bind(R.id.rg_client_status)
    RadioGroup statusRadio;
    @Bind(R.id.rg_clue_sort)
    RadioGroup clueRadio;
    @Bind(R.id.rg_manner)
    RadioGroup mannerRadio;
    @Bind(R.id.rg_def_reason)
    FlowRadioGroup reasonRadio;
    @Bind(rlty_def_reason)
    RelativeLayout reasonRel;
    @Bind(R.id.rlty_car_price)
    RelativeLayout priceRel;
    @Bind(R.id.ed_car_price)
    EditText priceEdit;
    @Bind(R.id.rbtn_defeated)
    RadioButton defRbtn;
    @Bind(R.id.rbtn_go_on)
    RadioButton gnRbtn;
    @Bind(R.id.rbtn_bj_deal)
    RadioButton bjRbtn;
    @Bind(R.id.recycler_photo)
    RecyclerView photoRecycler;
    private DateTimeDialog dateTimeDialog;
    private SelectPhotoPop photoPop;
    protected static final int REQUEST_CODE_CHOOSE = 24;
    protected static final int CAMERA_SYSTEM_CODE = 23;
    protected static final int CAMERA_REQUEST_CODE = 1;
    private int dispatch_status;
    private int follow_type;
    private int tourists_type;
    private int dispatch_type;
    private int soldType;
    private long follow_time;
    private String fileName;
    private String filePath;
    private int type;
    private FollowPhotoAdapter photoAdapter;
    List<CarSourcePhotoBean> photoBeanList = new ArrayList<>();
    private int currentIndex;
    private Intent bigPhotoIntent;
    private String photoPath;
    private Uri uri;
    @Override
    protected int getLayout() {
        return R.layout.activity_add_follow;
    }

    @Override
    protected void initEventAndData() {
//        dispatch/{订单id}/follow/
        bigPhotoIntent = new Intent(this, BigCarSourcePhotoActivity.class);//跳转到大图
        photoPop = new SelectPhotoPop(this, popListener);
        photoBeanList.add(new CarSourcePhotoBean("-1", "", "更多"));
        photoAdapter = new FollowPhotoAdapter(this, R.layout.layout_item_follow_photo, photoBeanList);
        photoAdapter.setOnItemClickListener(this);
        photoRecycler.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        photoRecycler.setAdapter(photoAdapter);
        dateTimeDialog = new DateTimeDialog(this, this);
        title.setText("添加跟进");
        type = getIntent().getIntExtra("TYPE", 1);
        returnLin.setVisibility(View.VISIBLE);
        typeRadio.setOnCheckedChangeListener(this);
        statusRadio.setOnCheckedChangeListener(this);
        clueRadio.setOnCheckedChangeListener(this);
        mannerRadio.setOnCheckedChangeListener(this);
        reasonRadio.setOnCheckedChangeListener(this);
        if (type == 2) {
            // 1，继续跟进,2，已建单,3，无效
            gnRbtn.setText("继续跟进");
            bjRbtn.setText("已建单");
            defRbtn.setText("无效");
        }
    }
    protected void refreshImage(String url, int index, String fileName) {
        Logger.d("filePath--"+url);
        if (photoBeanList.get(index).getPhotoName().equals("更多")) {        //没有图片名就不添加图片名
            photoBeanList.set(index, new CarSourcePhotoBean(photoBeanList.get(index).getId(), url, fileName));
        } else {
            photoBeanList.set(index, new CarSourcePhotoBean(photoBeanList.get(index).getId(), url, fileName));
        }
        if (index + 1 == photoBeanList.size()) {   //如果点击的是最后一张，那么就要多添加一张更多
            photoBeanList.add(new CarSourcePhotoBean("-1", "", "更多"));
        }
        photoAdapter.refresh(photoBeanList);
    }

    @Override
    protected void createPresenter() {
        getFollow();
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(photoBeanList.get(position).getPhoto())) {
            //如果没有图片，打开popupWindow
            photoPop.showAtLocation(findViewById(R.id.liner_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
//         //跳转大图
            bigPhotoIntent.putExtra("photoUrl", photoBeanList.get(position).getPhoto());
            startIntent(bigPhotoIntent, RequestAndResultCode.CARSURFACEPHOTOFRAGMENT_TO_BIGCARSOURCEPHOTOACTIVITY_REQUEST);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @OnClick({R.id.iv_return, R.id.btn_save, R.id.rlty_next_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                finish();
                break;
            case R.id.btn_save:
                uploadImage();
                addFollow();
                break;
//            case R.id.fresc_manner_photo:
//                photoPop = new SelectPhotoPop(this, popListener);
//                photoPop.showAtLocation(findViewById(R.id.liner_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                break;
            case R.id.rlty_next_time:
                if (dateTimeDialog != null) {
                    dateTimeDialog.show();
                }
                break;
        }
    }

    private void uploadImage() {
        fileName ="";
        for (int i = 0; i < photoBeanList.size() - 1; i++) {
            String photoPath = photoBeanList.get(i).getPhoto();//.substring(1);
            fileName += photoBeanList.get(i).getPhotoName() + ",";
            Logger.d("fileName=="+fileName);
            if (photoPath.startsWith("file:/")) {
                photoPath = photoBeanList.get(i).getPhoto().substring(6);
            }
            AliYunUtils.aLiYunUpLoadFollow(this,
                    photoBeanList.get(i).getPhotoName(),//图片名 这里的 PhotoName()的值和  fileName一样
                    photoPath ,type   //图片路径
                    , aliyunListener);
        }
    }

    private AliYunUtils.OnALiYunUpLoadListener aliyunListener = new AliYunUtils.OnALiYunUpLoadListener() {
        @Override
        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            CustomLog.d("上传进度 =" + ((currentSize * 100) / totalSize) + "%");
        }

        @Override
        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
            CustomLog.d("上传成功 = " + request.getObjectKey());
        }

        @Override
        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
            CustomLog.d("上传失败 = " + request.getObjectKey());
        }
    };

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        markType(checkedId);
        Logger.d("follow_type===" + follow_type);
    }

    private void markType(int checkedId) {
        Logger.d("follow_type===" + follow_type);
        switch (checkedId) {
            case R.id.rbtn_personal:
                Logger.d("geren");//个人
                tourists_type = 1;
                break;
            case R.id.rbtn_trader:               //商家
                tourists_type = 2;
                break;
            case R.id.rbtn_go_on:
                //继续带看
                dispatch_status = 1;
                reasonRel.setVisibility(View.GONE);
                failLin.setVisibility(View.GONE);
                priceRel.setVisibility(View.GONE);
                priceEdit.getText().clear();
                soldType = 0;
                break;
            case R.id.rbtn_bj_deal:               //博精成交
                dispatch_status = 2;
                reasonRel.setVisibility(View.GONE);
                failLin.setVisibility(View.GONE);
                priceRel.setVisibility(View.VISIBLE);
                soldType = 0;
                break;
            case R.id.rbtn_defeated:             //战败
                dispatch_status = 3;
                reasonRel.setVisibility(View.VISIBLE);
                failLin.setVisibility(View.VISIBLE);
                priceRel.setVisibility(View.GONE);
                priceEdit.getText().clear();
                break;
            case R.id.rbtn_important_clue:               //重要线索
                dispatch_type = 1;
                break;
            case R.id.rbtn_ordinary_clue:               //普通线索
                dispatch_type = 2;
                break;
            case R.id.rbtn_froward_clue:               //远期线索
                dispatch_type = 3;
                break;
            case R.id.rbtn_to_shop:               //到店
                follow_type = 1;
                break;
            case R.id.rbtn_call_phone:               //电话
                follow_type = 2;
                break;
            case R.id.rbtn_weixin:               //微信
                follow_type = 3;
                break;
            case R.id.rbtn_message:               //短信
                follow_type = 4;
                break;
            case R.id.rbtn_youxin_deal:               //优信成交
                soldType = 1;
                break;
            case R.id.rbtn_kanche_deal:               //看车成交
                soldType = 2;
                break;
            case R.id.rbtn_dealer_deal:               //车商成交
                soldType = 3;
                break;
            case R.id.rbtn_give_up:               //放弃
                soldType = 4;
                break;
            case R.id.rbtn_other:               //其他
                soldType = 5;
                break;
        }
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    checkPremission();
                    break;
                case R.id.rlty_select_album:    //选择相册
                    Matisse.from(FollowActivity.this)
                            .choose(MimeType.ofImage())
                            .countable(true)
                            .maxSelectable(1)
//                          .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .gridExpectedSize(
                                    getResources().getDimensionPixelSize(R.dimen.dimen_120))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };

    private void checkPremission() {
        final String permission = Manifest.permission.CAMERA;  //相机权限
        final String permission1 = Manifest.permission.WRITE_EXTERNAL_STORAGE; //写入数据权限
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, permission1) != PackageManager.PERMISSION_GRANTED) {  //先判断是否被赋予权限，没有则申请权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {  //给出权限申请说明
                ActivityCompat.requestPermissions(FollowActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE);
            } else { //直接申请权限
                ActivityCompat.requestPermissions(FollowActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE); //申请权限，可同时申请多个权限，并根据用户是否赋予权限进行判断
            }
        } else {  //赋予过权限，则直接调用相机拍照
            openCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {  //申请权限的返回值
            case CAMERA_REQUEST_CODE:
                int length = grantResults.length;
                final boolean isGranted = length >= 1 && PackageManager.PERMISSION_GRANTED == grantResults[length - 1];
                if (isGranted) {  //如果用户赋予权限，则调用相机
                    camera();
                } else { //未赋予权限，则做出对应提示
                    showToast("打开相机失败，没有权限");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void openCamera() {  //调用相机拍照
        Intent intent = new Intent();
        fileName = getObjectKey() + ".jpg";
        photoPath = Environment.getExternalStorageDirectory() + "/pinggushi/" + fileName;
        uri = Uri.fromFile(new File(photoPath));
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, CAMERA_SYSTEM_CODE);//启动拍照
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            Uri selectedImage = mSelected.get(0);
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            c.close();
            final File file1Path = new File(imagePath);
            Luban.with(this)
                    .load(file1Path)                 //传人要压缩的图片//设定压缩档次，默认三挡
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            Logger.d("压缩");
                        }

                        @Override
                        public void onSuccess(File file) {
                            Logger.d("压缩完成++" + file.getAbsolutePath());
                            copyFile(file, file1Path, true);
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过去出现问题时调用
                        }
                    }).launch();    //启动压缩
            filePath = imagePath;
            fileName = getObjectKey() + ".jpg";
        } else if (requestCode == CAMERA_SYSTEM_CODE && resultCode == RESULT_OK) {
//            fileName = getObjectKey() + ".jpg";
//            Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/pinggushi/",
//                    fileName));
//            Bundle bundle = data.getExtras();
//            Bitmap bitmap = (Bitmap) bundle.get("data");
//            BitmapUtil.saveImageToGallery(mContext, bitmap, fileName,false);
//            filePath = uri.getPath();
            if (!TextUtils.isEmpty(photoPath)) {
//                Bitmap bm = BitmapFactory.decodeFile(photoPath);
//                Logger.d("Bitmap==" + bm.getHeight());
//                Logger.d("Bitmap==" + bm.getWidth());
                filePath = photoPath;
                final File file1Path = new File(photoPath);
                Luban.with(this)
                        .load(file1Path)                 //传人要压缩的图片//设定压缩档次，默认三挡

                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                Logger.d("压缩");
                            }
                            @Override
                            public void onSuccess(File file) {
                                Logger.d("压缩完成++" + file.getAbsolutePath());
//                                copyFile(file, file1Path, true);
                                // TODO 压缩成功后调用，返回压缩后的图片文件
                            }

                            @Override
                            public void onError(Throwable e) {
                                // TODO 当压缩过去出现问题时调用
                            }
                        }).launch();    //启动压缩
            }
        }
        if (!TextUtils.isEmpty(fileName)) {
            refreshImage(filePath, currentIndex, fileName);
        }
    }

    @Override
    public void onDateSet(Date date) {
        nextTimeTV.setText(TimeUtils.date2String(date));
        follow_time = TimeUtils.date2Millis(date) / 1000;
        Logger.d(follow_time + "");
    }

    private void addFollow() {
        String content = contentEdit.getText().toString();
        if (TextUtils.isEmpty(content)) {
            showToast("填写跟进内容");
            return;
        }
        String dispatchId = CustomSharedPreferences.getString(this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        HashMap<String, Object> build = new MapUtil()
                .put("dispatch_id", dispatchId)
                .put("type", type)
                .put("dispatch_status", dispatch_status)
                .put("content", content)
                .put("follow_type", follow_type)
                .put("tourists_type", tourists_type)
                .put("dispatch_type", dispatch_type)
                .put("path", fileName)
                .put("next_follow_time", follow_time)
                .put("soldPrice", priceEdit.getText().toString())
                .put("soldType", soldType)
                .put("fail_summary", summaryEdit.getText().toString())
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(FollowActivity.this, build).create(IApiActivityRequest.class).addFollow(),
                new BaseSubscriber<TokenBean>(FollowActivity.this) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        if (o.getStatus_code() == 0) {
                            setResult(11);
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        cancelLoading();
                    }

                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onCompleted() {
                        cancelLoading();
                    }
                });
    }

    private void getFollow() {
        String dispatchId = CustomSharedPreferences.getString(this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        HashMap<String, Object> build = new MapUtil()
                .put("dispatch_id", dispatchId)
                .put("type", type)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(FollowActivity.this, build).create(IApiActivityRequest.class).getFollowInfo(),
                new BaseSubscriber<TokenBean<FollowInfoBean>>(FollowActivity.this) {
                    @Override
                    public void onSuccess(TokenBean<FollowInfoBean> o) {
                        if (o.getData() != null) {
                            dispatch_type = o.getData().getDispatch_type();
                            tourists_type = o.getData().getTourists_type();
                            dispatch_status = o.getData().getDispatch_status();
                            if (dispatch_type == 1) {
                                ((RadioButton) clueRadio.getChildAt(0)).setChecked(true);
                            } else if (dispatch_type == 2) {
                                ((RadioButton) clueRadio.getChildAt(1)).setChecked(true);
                            } else {
                                ((RadioButton) clueRadio.getChildAt(2)).setChecked(true);
                            }
                            if (tourists_type == 1) {
                                ((RadioButton) typeRadio.getChildAt(0)).setChecked(true);
                            } else {
                                ((RadioButton) typeRadio.getChildAt(1)).setChecked(true);
                            }
                            if (dispatch_status == 1) {
                                ((RadioButton) statusRadio.getChildAt(0)).setChecked(true);
                            } else if (dispatch_status == 2) {
                                ((RadioButton) statusRadio.getChildAt(1)).setChecked(true);
                            } else {
                                ((RadioButton) statusRadio.getChildAt(2)).setChecked(true);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }

                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onCompleted() {
                        cancelLoading();
                    }
                }

        );
    }
    public void camera() {
        Intent intent = new Intent();
        fileName = getObjectKey() + ".jpg";
        photoPath = Environment.getExternalStorageDirectory() + "/pinggushi/" + fileName;
            Uri pictureUri;
            File pictureFile = new File(photoPath);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, pictureFile.getAbsolutePath());
                pictureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
            }else {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                pictureUri = Uri.fromFile(pictureFile);
            }
            if (intent != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        pictureUri);
                startActivityForResult(intent, 1);
            }
    }
}
